package com.utils.gson.adapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeAdapter implements JsonSerializer<LocalTime>,JsonDeserializer<LocalTime>{
    @Override
    public JsonElement serialize(LocalTime LocalTime, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(LocalTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
    }
    //反序列化
    @Override
    public LocalTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return LocalTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("HH:mm:ss"));
        //下面这个也行，并且当时间带时区时就必须用下面这个
        //return ZonedDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString()).toLocalTime();
    }

}